import java.util.Arrays;

public class MyArrayList {
    private int[] elem; //数组存放数据
    private int usedSize; //变量记录有效元素个数

    //通过构造方法初始化数组，并指定数组大小
    public MyArrayList(int initialCapacity) {
        this.elem = new int[initialCapacity];
    }

    //打印顺序表
    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    //默认位置新增元素
    public void add(int value) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem,
                    this.elem.length * 2);
        }
        this.elem[this.usedSize] = value;
        this.usedSize++;
    }
    public boolean isFull() {
        if (this.usedSize == this.elem.length) {
            return true;
        }
        return false;
    }
    //指定位置新增元素
    public void add(int pos, int value) {
        //判断pos位置是否合法
        if (pos < 0 || pos > usedSize) {
            throw new PosException(pos + " 位置不合法！");
        }
        //判断数组满没满
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem,
                    this.elem.length * 2);
        }
        //挪数据
        for (int i = this.usedSize; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        //插入值
        this.elem[pos] = value;
        this.usedSize++;
    }

    //判断是否包含某个元素
    public boolean contains(int find) {
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == find) return true;
        }
        return false;
    }

    //查找某个元素对应的位置
    public int indexOf(int find) {
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == find) return i;
        }
        return -1;
    }

    //获取pos位置的元素
    public int get(int pos) {
        checkPos(pos);
        return elem[pos];
    }
    private void checkPos(int pos) {
        if (pos < 0 || pos >= usedSize) {
            throw new PosException(pos + "位置不合法！");
        }
    }

    //将pos位置 元素的值更新为value
    public void set(int pos, int value) {
        checkPos(pos);
        this.elem[pos] = value;
    }

    //获取顺序表长度
    public int size() {
        return this.usedSize;
    }

    //删除第一次出现的值
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        if (index == -1) {
            System.out.println("要删除的数据不存在");
            return;
        }
        for (int i = index; i < this.usedSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.usedSize--;
    }

    //清空顺序表
    public void clear() {
        this.usedSize = 0;
    }
}
